import api from '@/mao-ui/config/api.js';

let library = {
	success : function(data){
		console.log(data, 'success function');
	}
	,error : function(code, msg){
		console.log(code, 'errorCode');
		console.log(msg, 'errorMsg');
		if(code <= 500){
			uni.showToast({
				duration:2000,
				title:'错误：'+msg,
				icon:"none"
			})
		}
		return false;
	}
	,request : function(route, method, params, headers, success = false, error = false){
		if(success !== false && typeof success == 'function'){this.success = success;}
		if(error !== false && typeof error == 'function'){this.error = error;}
		let url = this.init(route, params);
		let self = this;
		uni.request({
			url:url,
			method:method,
			header:headers,
			data:params,
			success(ret) {ret.data[api.code_name] == api.success_code ? self.success(ret.data[api.data_name]) : self.error(ret.data[api.code_name], ret.data[api.msg_name]);},
			fail(e) {self.error(404, e.errMsg);}
		})
	}
	,init : function(route, param = {}){
		
		// 检查全局
		if (!api.domain){
			return this.error(400, 'domain invalid');
		} else if (api.code_name.length == 0) {
			return this.error(400, 'code_name invalid');
		} else if (api.msg_name.length == 0) {
			return this.error(400, 'msg_name invalid');
		} else if (api.success_code.length == 0) {
			return this.error(400, 'success_code invalid');
		} else if (api.data_name.length == 0) {
			return this.error(400, 'data_name invalid');
		} else if (Object.keys(api.interface).indexOf(route) == '-1'){
			return this.error(400, 'route '+route+' is undefined');
		}
		
		// 检查接口配置
		let urlConfig = this.getRouteConfig(route);
		if (Object.keys(urlConfig).indexOf('route') == '-1') {
			return this.error(401, 'route '+route+' is undefined');
		} else if (typeof urlConfig.route != 'string') {
			return this.error(401, 'route '+route+' type error');
		} else if (urlConfig.route.length == 0){
			return this.error(401, 'route '+route+' lenght error');
		}
		
		// 检查参数
		for(var i = 0; i < urlConfig.params.length; i++){
			var item = urlConfig.params[i];
			if(Object.keys(param).indexOf(item.name) == '-1'){
				return this.error(402, 'param '+item.title+' is undefined');
			} else if (item.type == 'array' && typeof param[item.name] != 'array'){
				return this.error(402, 'param '+item.title+' Not an array');
			} else if (item.type == 'object' && typeof param[item.name] != 'object'){
				return this.error(402, 'param '+item.title+' Not an object');
			}
		}
		
		
		return api.domain + urlConfig.route;
	},
	getRouteConfig : function (route) {
		let urlConfig = api.interface[route] || {};
		urlConfig.params = urlConfig.params || {};
		urlConfig.is_auth = urlConfig.is_auth || false;
		urlConfig.is_save_auth = urlConfig.is_save_auth || false;
		return urlConfig;
	},
	setAuth : function(name){
		
	},
	getAuth : function(name){
		
	}
}
export default library